package com.example.administrator.testproject.downM3U8;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.example.administrator.testproject.download.RxRetrofitApp;
import com.example.administrator.testproject.download.util.BaseUtils;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.util.ArrayList;
import java.util.List;


/**
 * 断点续传
 * 数据库工具类-geendao运用
 * Created by WZG on 2016/10/25.
 */

public class LiteDbM3U8DownUtil extends BaseUtils{

    private static LiteDbM3U8DownUtil db;
    private final static String dbName = "edu_db";
    private Context context;
    private LiteOrm liteOrm;

    public LiteDbM3U8DownUtil() {
        context= RxRetrofitApp.getApplication();
        liteOrm = LiteOrm.newCascadeInstance(context, dbName);
    }

    /**
     * 获取单例
     * @return
     */
    public static LiteDbM3U8DownUtil getInstance() {
        if (db == null) {
            synchronized (LiteDbM3U8DownUtil.class) {
                if (db == null) {
                    db = new LiteDbM3U8DownUtil();
                }
            }
        }
        return db;
    }

    /**
     * 获取可读数据库
     */
    private SQLiteDatabase getReadableDatabase() {
        SQLiteDatabase db = liteOrm.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     */
    private SQLiteDatabase getWritableDatabase() {
        SQLiteDatabase db = liteOrm.getWritableDatabase();
        return db;
    }

    public  List<ItemM3U8Ts> queryDownAll() {
        List<ItemM3U8Ts> qb = liteOrm.query(ItemM3U8Ts.class);
        return qb;
    }

    public void save(ItemM3U8Ts info){
        liteOrm.insert(info);
    }

    public void update(ItemM3U8Ts info){
        liteOrm.update(info);
    }

    public void deleteDowninfo(LiteM3U8DownInfo info){
        liteOrm.delete(info);
    }


    public ItemM3U8Ts queryDownBy(long Id) {
        //模糊查询
        QueryBuilder<ItemM3U8Ts> qb =
                new QueryBuilder<ItemM3U8Ts>(ItemM3U8Ts.class)
                        .whereEquals("id", Id);

        ArrayList<ItemM3U8Ts> query = liteOrm.query(qb);
        if(query.isEmpty()){
            return null;
        }else{
            return query.get(0);
        }
    }


}
